#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
# @FileName  :route_jobs.py
# @Time      :2022/4/25 2:25 PM
# @Author    :Toliong toliong@foxmail.com
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from apis.version1.route_login import get_current_user_from_token

from db.session import get_db
from db.models.jobs import Job
from db.models.users import User
from db.repository.jobs import create_new_job, retreive_job, list_jobs
from db.repository.jobs import update_job_by_id, delete_job_by_id
from schemas.jobs import JobCreate, ShowJob
from core.config import lg

router = APIRouter()


@router.post("/create-job/", response_model=ShowJob)
def create_job(
        job: JobCreate,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user_from_token)
):
    job = create_new_job(job=job, db=db, owner_id=current_user.id)
    return job


@router.get("/get/{id}", response_model=ShowJob)
def read_job(id:int, db: Session = Depends(get_db)):
    job = retreive_job(id=id, db=db)
    lg.info(job.company_url)
    if not job:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Job with this id {id} does not exist")
    return job


@router.get("/all", response_model=list[ShowJob])
def read_jobs(db: Session = Depends(get_db)):
    jobs = list_jobs(db=db)
    return jobs


@router.post("/update/{job_id}")
def update_job(job_id: int, job: JobCreate, db: Session = Depends(get_db)):
    current_user_id = 1
    message = update_job_by_id(job_id=job_id, job=job, db=db, owner_id=current_user_id)
    if not message:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"job with id {job_id} not found")
    return {"message": "Successfully update data."}


@router.delete("/delete/{job_id}")
def delete_job(job_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_from_token)):
    job = retreive_job(job_id=job_id, db=db)
    print(f"delete job from user id is: {current_user.id}")
    if not job:
        return HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Job with {id} does not exist")
    print(job.owner_id, current_user.id, current_user.is_superuser)
    if job.owner_id == current_user.id or current_user.is_superuser:
        delete_job_by_id(job_id=job_id, db=db, owner_id=current_user.id)
        return {"msg":"Successfully deleted."}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                        detail=f"You are not permitted!!!!")
